// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 设备升级价格配置
const UPGRADE_PRICES = {
  egg: [0, 100, 300, 600, 1000, 1500],   // 第0级不存在，从1级开始
  bread: [0, 100, 300, 600, 1000, 1500],
  coffee: [0, 100, 300, 600, 1000, 1500]
}

// 设备最大等级
const MAX_LEVEL = 5

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const equipmentType = event.equipmentType  // 'egg', 'bread', 'coffee'
  
  // 验证设备类型
  if (!['egg', 'bread', 'coffee'].includes(equipmentType)) {
    return {
      success: false,
      error: '无效的设备类型'
    }
  }

  try {
    // 获取用户当前数据
    const userResult = await db.collection('users').doc(openid).get()
    const userData = userResult.data
    
    // 获取当前设备等级
    const currentLevel = userData.equipment[equipmentType].level || 1
    
    // 检查是否已达到最高等级
    if (currentLevel >= MAX_LEVEL) {
      return {
        success: false,
        error: '设备已达到最高等级'
      }
    }
    
    // 计算升级所需金币
    const upgradeCost = UPGRADE_PRICES[equipmentType][currentLevel]
    
    // 检查金币是否足够
    if (userData.coins < upgradeCost) {
      return {
        success: false,
        error: '金币不足'
      }
    }
    
    // 更新设备等级和金币数量
    const updateData = {
      coins: userData.coins - upgradeCost,
      [`equipment.${equipmentType}.level`]: currentLevel + 1,
      updateTime: db.serverDate()
    }
    
    await db.collection('users').doc(openid).update({
      data: updateData
    })
    
    // 获取更新后的用户数据
    const updatedUserResult = await db.collection('users').doc(openid).get()
    
    return {
      success: true,
      data: {
        equipment: updatedUserResult.data.equipment,
        coins: updatedUserResult.data.coins,
        upgradedEquipment: equipmentType,
        newLevel: currentLevel + 1
      }
    }
  } catch (err) {
    return {
      success: false,
      error: err
    }
  }
}